package com.ruoyi.jihuo.quzrtz;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.JhTmProductsOnSale;
import com.ruoyi.jihuo.service.IJhTmAccountService;
import com.ruoyi.jihuo.service.IJhTmProductsOnSaleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class SubmitItem {

    private static final Logger log = LoggerFactory.getLogger(SubmitItem.class);
    @Autowired
    private CallTaoApiService callTaoApiService;

    @Autowired
    private IJhTmAccountService jhTmAccountService;

    @Autowired
    private IJhTmProductsOnSaleService jhTmProductsOnSaleService;

    private static final Queue<JSONObject> queue = new ConcurrentLinkedQueue<>();

    public Queue<JSONObject> getQueue() {
        return queue;
    }

    public void submit() {
        JSONObject item = queue.poll();
        if (item != null && !item.isEmpty()) {
            Long productId = item.getLong("productId");
            Long cid = item.getLong("categoryId");
            JhTmAccount jhTmAccount = item.getObject("tmAccount", JhTmAccount.class);
            String itemInfo = item.getString("schema");
            try {
                String s = callTaoApiService.submitItem(jhTmAccount, cid, productId, itemInfo);
                int jhTrafficNum = jhTmAccount.getJhTrafficNum();
                jhTmAccount.setJhTrafficNum(jhTrafficNum - 1);
                jhTmAccountService.updateJhTmAccount(jhTmAccount);

                JhTmProductsOnSale productsOnSale = item.getObject("productsOnSale", JhTmProductsOnSale.class);
                productsOnSale.setJhStatus("2");
                log.info("提交成功：{}", s);
            } catch (ServiceException e) {
                String message = e.getMessage();
                // 连续调用超过1s，重试就行 (按appkey 来的，只要用三方接口商，就大概率出现这个问题)
                if (message.contains("This ban will last for 1 more seconds")) {
                    queue.add(item);
                } else {
                    // 失败逻辑，估计得需要改代码了
                    log.error("提交失败：{}", message);
                    throw new ServiceException(e.getMessage());
                }

            }
        } else {
            log.info("当前队列为空，跳过");
        }
    }
}
